<template>
  <DetailsFormBox :title="page.title" :type="route.query.type" :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: !isEdit,
      click: getForm,
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      hidden: !isEdit,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '审核通过',
      icon: '',
      type: 'success',
      hidden: route.query.type !== '4',
      click: (form: any) => {
        proxy.$messageBox('是否审核通过，请确认！', () => {
          proxy.$api.GoodsPurchaseOrder.SurePurchaseOrder({
            entityID: form.purchaseID,
          })
            .then((res: any) => {
              proxy.$message('审核通过');
              closeBtn()
            })
            .catch(() => { });
        });
      },
    },
    {
      title: '审核拒绝',
      icon: '',
      type: 'danger',
      hidden: route.query.type !== '4',
      click: (form: any) => {
        proxy.$messageInputBox('请填写拒绝原因！', (value: string) => {
          setState(form, 3, '拒绝成功', value)
        });
      },
    },
  ]" :formInfo="[
    {
      label: '创建人员',
      value: 'createPersonName',
    },
    {
      label: '创建时间',
      value: 'createTime',
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <div class="p-12">
        <OrderInfo :data="data.productOrder" :produceTaskBillNo="route.query.produceTaskBillNo" />
        <CellBox title="基本信息" isTop>
          <FlexBox>
            <ElFormItemBox label="采购单号" prop="purchaseOrderNo">
              <ElInputBox :data="form" dataName="purchaseOrderNo" placeholder="系统自动生成" disabled />
            </ElFormItemBox>
            <ElFormItemBox label="供应商" prop="supplierCode" isRules>
              <ElSelectBox :data="form" dataName="supplierCode" :options="options.supplier" :disabled="!isEdit"
                @changeBtn="() => {
                  form.purchaseDetailsList = []
                }" />
            </ElFormItemBox>
            <ElFormItemBox label="采购类型" prop="purchaseType" isRules>
              <ElSelectBox :data="form" dataName="purchaseType" :options="options.orderType" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="期望到货" prop="expectArrivalTime" isRules>
              <ElDayBox :data="form" dataName="expectArrivalTime" :disabled="!isEdit" />
            </ElFormItemBox>
            <ElFormItemBox label="采购备注" prop="purchaseDesc" class="wAuto">
              <ElInputBox :data="form" dataName="purchaseDesc" type="textarea" :disabled="!isEdit" />
            </ElFormItemBox>
          </FlexBox>
        </CellBox>
        <CellBox title="单据明细" isTop>
          <GoodList :height="450" :data="{
            disabled: !isEdit,
            rowKey: 'specificationCode',
            isColumn: [],
            search: {
              supplierCode: form.supplierCode,
            },
            prop: 'purchaseDetailsList',
            tbody: form.purchaseDetailsList,
            thead: [
              {
                label: '采购数量',
                prop: 'planPurchaseQuantity',
                formType: 'number',
                isRules: true,
                width: 160,
              },
              {
                label: '计价数量',
                prop: 'PricingQuantity',
                isRules: true,
                align: 'center',
                width: 100,
                value: (row: any) => {
                  return proxy.$count(`${row.planPurchaseQuantity || 0}*${row.specificationJsValue || 0}`)
                }
              },
              {
                label: '计价单位',
                prop: 'priceUnitName',
                width: 120,
                align: 'center',
              },
              {
                label: '含税单价',
                prop: 'purchasePrice',
                align: 'center',
                width: 160,
              },
              {
                label: '含税小计',
                prop: 'taxIncludedSubtotal',
                align: 'center',
                width: 160,
                value: (row: any) => {
                  return proxy.$count(`${row.planPurchaseQuantity || 1}*${row?.specificationJsValue || 1}*${row?.purchasePrice || 1}`, 9)
                }
              },
              {
                label: '未税单价',
                prop: 'purchasePriceBeforeTax',
                align: 'center',
                width: 160,
              },
              {
                label: '未税小计',
                prop: 'taxExcludedSubtotal',
                align: 'center',
                width: 160,
                value: (row: any) => {
                  return proxy.$count(`${row.planPurchaseQuantity || 1}*${row?.specificationJsValue || 1}*${row?.purchasePriceBeforeTax || 1}`, 9)
                }
              },
              {
                label: '备注',
                prop: 'purchaseDesc',
                formType: 'textarea'
              },
            ],
            operation: [
              {
                label: '复制',
                icon: 'CopyDocument',
              },
              {
                label: '删除',
                icon: 'Delete',
              },
            ]
          }" @selectBtn="(rowArr: any) => {
            let _arr = rowArr.map((el: any) => ({
              supplierCode: el.supplierCode, // 供应商编码
              goodsCode: el.goodsCode, // 物料编码
              specificationCode: el.specificationCode, // 物料规格编码
              purchasePrice: el.goodsPrice || 0, // 含税单价
              purchasePriceBeforeTax: el.goodsPriceBeforeTax || 0, // 未税单价(未税单价)
              planPurchaseQuantity: null, // 计划采购数量
              purchaseDesc: '', // 采购说明
            }))
            if (!!!form.supplierCode) {
              form.supplierCode = _arr[0].supplierCode
              _arr = _arr.filter((el: any) => el.supplierCode === form.supplierCode)
            }
            form.purchaseDetailsList.push(..._arr)
          }">
          </GoodList>
        </CellBox>
      </div>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import page from '../page.ts'; // 引入逻辑
import '../pageCss.scss'; // 引入样式
import { useListComponent } from '../pageTs'; // 引入逻辑
const { options } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  mainPage: 1,
  form: {
    purchaseOrderNo: "", // 采购单号
    purchaseType: "", // 采购类型
    supplierCode: "", // 供应商编码
    expectArrivalTime: "", // 期望到货时间，格式：yyyy-MM-dd
    purchaseDesc: "", // 采购说明
    purchaseDetailsList: [
      // {
      //   goodsCode: "", // 物料编码
      //   specificationCode: "", // 物料规格编码
      //   goodsPrice: 0.0, // 物料单价
      //   goodsPriceBeforeTax: 0.0, // 物料单价(未税单价)
      //   planPurchaseQuantity: 0.0, // 计划采购数量
      //   purchaseDesc: "", // 采购说明
      //   dateOfManufacture: "2025-05-19" // 生产日期
      // }
    ]
  },
});
const isEdit = ref(true)

import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//获取数据
const getForm = async () => {
  let _query: any = route.query
  setLoading()
  //获取工单信息
  //是否新建
  if (!!!_query.purchaseID) {
    data.loading = false
    return
  }
  proxy.$api.GoodsPurchaseOrder.GetSinglePurchaseOrder({
    queryBy: 1,
    queryValue: _query.purchaseID,
  })
    .then((res: any) => {
      proxy.$message('获取成功')
      isEdit.value = (['1', '2'].includes(_query.type) && res.purchaseOrderState === 0)
      data.form = res
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const saveBtn = (form: any, isConfirm: boolean = false) => {
  const _form: any = {
    purchaseID: form.purchaseID, // id
    purchaseOrderNo: form.purchaseOrderNo, // 采购单号
    purchaseType: form.purchaseType, // 采购类型
    supplierCode: form.supplierCode, // 供应商编码
    expectArrivalTime: form.expectArrivalTime, // 期望到货时间，格式：yyyy-MM-dd
    purchaseDesc: form.purchaseDesc, // 采购说明
    purchaseDetailsList: form.purchaseDetailsList.map((el: any) => (
      {
        goodsCode: el.goodsCode, // 物料编码
        specificationCode: el.specificationCode, // 物料规格编码
        goodsPrice: el.purchasePrice, // 含税单价
        goodsPriceBeforeTax: el.purchasePriceBeforeTax, // 未税单价
        planPurchaseQuantity: el.planPurchaseQuantity, // 计划采购数量
        purchaseDesc: el.purchaseDesc, // 采购说明
      }
    ))
  }
  switch (route.query.type) {
    case '1'://新建
      proxy.$api.GoodsPurchaseOrder.AddPurchaseOrder({
        ..._form,
        purchasePersonCode: proxy.$user.userCode,//采购人员编码
      })
        .then((res: any) => {
          _form.dataBillID = res
          _sun()
        })
        .catch(() => { });
      break;
    case '2'://编辑
      proxy.$api.GoodsPurchaseOrder.UpdatePurchaseOrder(_form)
        .then((res: any) => {
          _form.dataBillID = res
          _sun()
        })
        .catch(() => { });
      break;

    default:
      break;
  }

  function _sun() {
    proxy.$message('保存成功')
    closeBtn()
  }
};

const closeBtn = () => {
  sendMsg('save', true);
  //  getForm()
  window.close();
};
//更改状态
const setState = (row: any, state: number = 0, message: string = '操作成功', cancelReason?: string) => {
  proxy.$api.GoodsPurchaseOrder.VoidPurchaseOrder({
    purchaseID: row.purchaseID,
    cancelReason: cancelReason,
    purchaseOrderState: state, //采购单状态：3已拒绝；4已作废
  })
    .then((res: any) => {
      proxy.$message(message);
      closeBtn()
    })
    .catch(() => { });
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};

onMounted(() => {
  getForm();
});
</script>
